<!DOCTYPE html>
<html>
    <head>
        <meta charset='UTF-8'>
        <!-- Képernyő nagyításának tiltása érintőképernyős eszközökön. -->
        <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'>
        <title>#!PAGE_TITLE!#</title>
        <style>html, body {margin:0;padding:0;border:0;overflow:hidden;font-size:100%;font-family:monospace;color:white;}</style>
        <style>
            /* Link formázása gombbá. */
            .link-button {
                pointer-events: auto;
                background-color: black;
                border: 1px solid white;
                border-radius: 2px;
                color: black;
                padding: 10px 10px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 15px;
                margin: 2px 2px;
                -webkit-transition-duration: 0.15s;
                transition-duration: 0.15s;
                cursor: default;
                color: white;
                font-family: monospace;
                -webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;
            }
            .link-button:hover {
                background-color: white;
                color: black;
            }
            .link-button:active {
                text-decoration: underline;
            }
            /* Beviteli mező és gomb formázása. */
            input[type='text'],input[type=button] {
                pointer-events: auto;
                -webkit-transition-duration: 0.3s;
                transition-duration: 0.3s;
                background-color: black;
                color: white;
                border-radius: 2px;
                border: 1px solid white;
                padding: 2px 2px;
                margin: 2px 2px;
                font-family: monospace;
                outline: none;
            }
            input[type='text']:focus, input[type=button]:hover {
                background-color: white;
                color: black;
            }
            input[type='text'] {
                cursor: text;
            }
            input[type=button]:active {
                text-decoration: underline;
            }
            /* Chat üzenetek tárolója. */
            .chat-messages {
                color: white;
                font-family: monospace;
                cursor: default;
                pointer-events: none;
                -webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;
                border-radius: 2px;
                background: rgba(0, 0, 0, .9);
            }
        </style>

        <!-- Könyvtárak betöltése. -->
        <script src="createjs.js"></script>


        <script>
            // Debug.
            var debug = true;
            function toDebug(msg) {if (debug) console.log('DEBUG: ' + msg); };
            // Nézeti ablak.
            var viewport = {x:0, y:0, oldX:0, oldY:0, scale:1.0, tlx:0, tly:0, brx:0, bry:0};
            function updateViewport() {
                viewport.tlx = screenToWorldX(0);
                viewport.tly = screenToWorldY(0);
                viewport.brx = screenToWorldX(stage.canvas.width);
                viewport.bry = screenToWorldY(stage.canvas.height);
            };
            var isPanning = false;
            var panning = {xFrom:0, yFrom:0, xTo:0, yTo:0};
            var stage;
            // Meteorok tárolója.
            var meteors = {};
            // Meteor létrehozása (azonosító, sugár, globális pozíció).
            function createMeteor(meteorID, r, gx, gy) {
                var meteor = new createjs.Shape();
                meteor.graphics.beginFill('white').drawCircle(0, 0, r);
                meteor.meteorID = meteorID;
                meteor.R = r;
                meteor.gx = gx;
                meteor.gy = gy;
                meteor.alpha = 0;
                transformObject(meteor);
                return meteor;
            };
            // Objektum transzformálása a nézeti ablak és a világ között.
            function screenUnitToWorld() {return Math.abs(screenToWorldX(1) - screenToWorldX(0)); };
            function worldUnitToScreen() {return Math.abs(worldToScreenX(1) - worldToScreenY(0)); };
            function worldToScreenX(x) {return viewport.scale * (viewport.x + x) + stage.canvas.width / 2; };
            function worldToScreenY(y) {return viewport.scale * (viewport.y - y) + stage.canvas.height / 2; };
            function screenToWorldX(x) {return  (x - (stage.canvas.width / 2) - viewport.scale * viewport.x) / viewport.scale; };
            function screenToWorldY(y) {return - (y - (stage.canvas.height / 2) - viewport.scale * viewport.y) / viewport.scale; };
            function transformObject(obj) {
                obj.x = worldToScreenX(obj.gx);
                obj.y = worldToScreenY(obj.gy);
                obj.scaleX = obj.scaleY = Math.max(0.1, viewport.scale);
            };
            // Objektumok transzformálása a nézeti ablak szerint.
            function transformObjects() {
            updateViewport();
            for (var k in meteors) {transformObject(meteors[k]);}
            };
            // Meteor hozzáadása a jelenethez.
            function addMeteor(meteor) {
                if (!meteors[meteor.meteorID]){
                    meteors[meteor.meteorID] = meteor; stage.addChild(meteor);
                    createjs.Tween.get(meteors[meteor.meteorID], {loop:false}).to({alpha:1}, 200, createjs.Ease.linear);
                }
                meteors[meteor.meteorID].gx = meteor.gx;
                meteors[meteor.meteorID].gy = meteor.gy;
                transformObject(meteors[meteor.meteorID]);
            };
            window.addEventListener('resize', resize, false);
            var meteorCounter = 4;
            function init() {
                stage = new createjs.Stage('canvas');
                createjs.Ticker.setFPS(60);
                createjs.Ticker.addEventListener('tick', stage);
                stage.on('stagemousedown', function(evt) {
                    if (0 == evt.nativeEvent.button) {
                        addMeteor(createMeteor('m' + (meteorCounter++), 10, screenToWorldX(evt.stageX), screenToWorldY(evt.stageY)));
                    }
                    if (1 == evt.nativeEvent.button) {
                        viewport.oldX = viewport.x;
                        viewport.oldY = viewport.y;
                        panning.xFrom = evt.stageX;
                        panning.yFrom = evt.stageY;
                        isPanning = true;
                    }
                });
                stage.on('stagemouseup', function(evt) {
                    if (1 == evt.nativeEvent.button) {isPanning = false; }
                    if (0 == evt.nativeEvent.button) {}
                });
                stage.on('stagemousemove', function(evt) {
                    if (isPanning) {
                        viewport.x = (viewport.oldX + screenToWorldX(evt.stageX) - screenToWorldX(panning.xFrom));
                        viewport.y = (viewport.oldY - screenToWorldY(evt.stageY) + screenToWorldY(panning.yFrom));
                        transformObjects();
                    }
                });
                var canvas = document.getElementById('canvas');
                canvas.addEventListener('mousewheel', mousewheel, false);
                canvas.addEventListener('DOMMouseScroll', mousewheel, false);
                resize();
                addMeteor(createMeteor('m1', 10, 0, 0));
                addMeteor(createMeteor('m2', 10, 50, 0));
                addMeteor(createMeteor('m3', 10, 0, 50));
            };
            function mousewheel(e) {
                var wheelDistance = function(evt){if (!evt) evt = event; var w = evt.wheelDelta, d = evt.detail; if (d){if (w) return w / d / 40 * d > 0?1: - 1; else return - d / 3; } else return w / 120; };
                var pos = [screenToWorldX(e.clientX), screenToWorldY(e.clientY)];
                var dl = screenUnitToWorld() * 200.0;
                var s = viewport.scale;
                var ds = Math.min((s * s * dl) / (s * dl + stage.canvas.width), (s * s * dl) / (s * dl + stage.canvas.height));
                viewport.scale += ds * (wheelDistance(e));
                viewport.scale = Math.max(viewport.scale, 0.001);
                viewport.x -= (pos[0] - screenToWorldX(e.clientX));
                viewport.y += (pos[1] - screenToWorldY(e.clientY));
                transformObjects();
            };
            function tick() {stage.update(); }
            function resize() {stage.canvas.width = window.innerWidth; stage.canvas.height = window.innerHeight; transformObjects(); }
        </script>
    </head>
    <body onload='init();'>
        <canvas id='canvas' style='cursor:crosshair;position:absolute;left:0px;top:0px;background-color:rgba(0, 0, 0, 1);'>#!DONT_SUPPORT_CANVAS!#</canvas>
        <div style='width:100%;height:100%;pointer-events:none;position:absolute;z-index:1'>
            <!-- Fő táblázat a GUI elemek igazításához. -->
            <table border=0 cellSpacing=0 cellPadding=0 style='width:100%;height:100%;'>
                <tr style='width:100%;'>
                    <td style='padding:5px;'><b><big><div id=userNameDiv style='cursor:default;pointer-events:auto;background-color:black;white-space:nowrap;width:auto;-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;'></div></big></b></td>
                    <td style='width:100%;'></td>
                    <td align=right><a href='/logout' class='link-button'>#!LOGOUT!#</a></td></tr>
                <tr style='height:100%;'>
                    <td colSpan=3 vAlign=bottom> <div id='chatMsgBox' class='chat-messages' style='margin-left:5px;overflow:hidden;max-width:20%;max-height:70%;'></div></td>
                </tr>
                <tr>
                    <td colSpan=3>
                        <table border=0 cellSpacing=0 cellPadding=0 style='width:100%;height:100%;'>
                            <tr style='pointer-events:auto;cursor:default;background-color:black;width:100%;'>
                                <td style='padding:5px;border-top:1px solid white;-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;'>
                                    #!MESSAGE!#:
                                </td>
                                <td style='width:100%;padding:5px;border-top:1px solid white;'>
                                    <input type='text' id='chatInput' maxlength='100' style='width:calc(100% - 10px);'>
                                </td>
                                <td style='padding:5px;border-top:1px solid white;'>
                                    <input id='sendChatMsgButton' type='button' value='#!SEND_MESSAGE!#'>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
            <script>
                // Üzenet érkezett.
                function isJSON(text){try{JSON.parse(text); return true; } catch (error){return false; }};
                var handleResponse = function(responseText) {
                    toDebug(responseText);
                    if ('' == responseText || !isJSON(responseText)) return;
                    // Üzenet átalakítása.
                    var response = JSON.parse(responseText);
                    for (var i in response) {
                        var o = response[i];
                        switch (o['a']) {
                        // Átirányítás érkezett.
                        case 'rd':
                            toDebug('redirected to: ' + o['d']['url']);
                            window.location.href = o['d']['url'];
                        break;
                        // Chat üzenet érkezett.
                        case 'cm':
                            var cmb = document.getElementById('chatMsgBox');
                            var count = (cmb.innerHTML.match(/<br>/g) || []).length;
                            if (count == messagesCount) cmb.innerHTML = cmb.innerHTML.substring(cmb.innerHTML.indexOf('<br>') + 4);
                            if (downloadinMessages) {
                                cmb.innerHTML = "";
                                downloadinMessages = false;
                            }
                            cmb.innerHTML = cmb.innerHTML + '<b><u>' + o['d']['user'] + '</u></b>: ' + unescape(o['d']['msg']) + '<br>';
                            cmb.scrollTop = cmb.scrollHeight;
                            break;
                        }
                    }
                };
                // Long-polling.
                var lp = function() {
                    toDebug('openResponseChannel()');
                    var xhrlp = new XMLHttpRequest();
                    xhrlp.open('POST', '/play', true);
                    xhrlp.responseType = 'text';
                    xhrlp.onreadystatechange = function (oEvent) {
                        if (xhrlp.readyState === 4) {
                            if (xhrlp.status === 200) {
                                handleResponse(xhrlp.responseText);
                            } else {
                                toDebug('Error:', xhrlp.statusText);
                                xhrlp.abort();
                            }
                            lp();
                        }
                    };
                    xhrlp.timeout = 0;
                    xhrlp.send('');
                };
                lp();
                var sendToServer = function(text) {
                    toDebug('sendToServer(' + text + ');');
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '/play', true);
                    xhr.responseType = 'text';
                    xhr.onload = function(){handleResponse(xhr.responseText); };
                    xhr.send(text);
                };
            </script>
            // Chat.
        </div>
        <script>
            var chatMsgBox = document.getElementById('chatMsgBox');
            var chatInput = document.getElementById('chatInput');
            chatInput.focused = false;
            chatInput.hasFocus = function(){return this.focused; };
            chatInput.onfocus = function(){this.focused = true; };
            chatInput.onblur = function(){this.focused = false; };
            var sendChatMsgButton = document.getElementById('sendChatMsgButton');
            var userNameDiv = document.getElementById('userNameDiv');
            userNameDiv.innerHTML = unescape('#!PLAYER_NAME!#');
            var sendMsgFunc = function(){if ('' != chatInput.value) {sendToServer(JSON.stringify({a:'cm', d:{msg:escape(chatInput.value)}})); chatInput.value = ''; }};
            sendChatMsgButton.onclick = function(){sendMsgFunc(); };
            // Enter lenyomása az üzenet beírásához/elküldéséhez.
            document.body.addEventListener('keydown', function(e){if (13 == e.keyCode){if (!chatInput.hasFocus()){chatInput.focus(); return; }sendMsgFunc(); chatInput.blur(); }});
        </script>
        // Scene.
        
        <script>
            chatMsgBox.innerHTML = '#!DOWNLOADING_CHAT_MESSAGES!#';
            var downloadinMessages = true;
            // Egyszerre megjelenő üzenetek száma.
            var messagesCount = 15;
            // Chat üzenetek letöltése.
            sendToServer(JSON.stringify({a:'gcm',d:{mc:messagesCount}}));
        </script>
    </body></html>